package com.jmb.waimao.scheduler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jmb.waimao.entity.EmailTask;
import com.jmb.waimao.service.EmailTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Scheduler for email tasks
 */
@Component
@Slf4j
public class EmailTaskScheduler {

    @Autowired
    private EmailTaskService emailTaskService;

    /**
     * Check for scheduled email tasks every minute
     */
    @Scheduled(cron = "0 * * * * ?")
    public void checkScheduledTasks() {
        log.debug("Checking for scheduled email tasks...");
        
        LocalDateTime now = LocalDateTime.now();
        
        // Find tasks that are scheduled to run now and are in Created status
        LambdaQueryWrapper<EmailTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmailTask::getStatus, 0) // Created
                    .le(EmailTask::getScheduledTime, now)
                    .eq(EmailTask::getDeleted, 0);
        
        List<EmailTask> tasksToExecute = emailTaskService.list(queryWrapper);
        
        if (!tasksToExecute.isEmpty()) {
            log.info("Found {} scheduled tasks to execute", tasksToExecute.size());
            
            for (EmailTask task : tasksToExecute) {
                log.info("Executing scheduled task: {}", task.getTaskName());
                emailTaskService.executeTask(task.getId());
            }
        }
    }
    
    /**
     * Clean up old tasks (older than 30 days) every day at midnight
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void cleanupOldTasks() {
        log.info("Cleaning up old email tasks...");
        
        LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
        
        // Find completed or failed tasks older than 30 days
        LambdaQueryWrapper<EmailTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EmailTask::getStatus, 2, 3) // Completed or Failed
                    .lt(EmailTask::getUpdateTime, thirtyDaysAgo)
                    .eq(EmailTask::getDeleted, 0);
        
        List<EmailTask> oldTasks = emailTaskService.list(queryWrapper);
        
        if (!oldTasks.isEmpty()) {
            log.info("Found {} old tasks to clean up", oldTasks.size());
            
            for (EmailTask task : oldTasks) {
                task.setDeleted(1);
                task.setUpdateTime(LocalDateTime.now());
            }
            
            emailTaskService.updateBatchById(oldTasks);
            log.info("Cleaned up {} old tasks", oldTasks.size());
        }
    }
}
